package org.argus.common.web.core.security;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.argus.common.core.text.Convert;
import org.argus.common.web.core.domain.LoginUser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT 处理相关的实现，所有用户当前业务域、权限等相关的信息都存放在JWT里
 * 
 * @Author 刘文/Cliff Liu
 * @Date 2024/5/1
 */
@Component
public class JwtMaintainer {

    @Value("${argus.encrypt.secret:Change_me_123}")
    private String secret;

    public static final String USER_ID_KEY = "userId";

    public static final String USERNAME_KEY = "username";

    /**
     * 业务域ID
     */
    public static final String DOMAIN_KEY = "domainId";

    /**
     * 角色列表 KEY
     */
    public static final String ROLES_KEY = "roles";

    /**
     * 用户类型 KEY
     */
    public static final String USER_TYPE_KEY = "userType";

    private SecureRandom secureRandom;

    @PostConstruct
    public void init() {
        secureRandom = new SecureRandom(secret.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 生成访问令牌
     * 
     * @param loginUser
     * @return
     */
    public String generateAccessToken(LoginUser loginUser) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(USER_ID_KEY, loginUser.getUserId());
        claims.put(USERNAME_KEY, loginUser.getUsername());
        claims.put(DOMAIN_KEY, loginUser.getDomainId());
        claims.put(ROLES_KEY, loginUser.getRoles());
        claims.put(USER_TYPE_KEY, loginUser.getUserType());
        return Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, secret).compact();
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token)
    {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }

    public String getUsername(String accessToken) {
        return getValue(parseToken(accessToken), USERNAME_KEY);
    }

    /**
     * 获取用户ID
     *
     * @param accessToken 访问令牌
     * @return 用户ID
     */
    public Long getUserId(String accessToken) {
        String idStr = getValue(parseToken(accessToken), USER_ID_KEY);
        return idStr != null ? Long.parseLong(idStr) : null;
    }

    public Long getDomainId(String accessToken) {
        String idStr = getValue(parseToken(accessToken), DOMAIN_KEY);
        return idStr != null ? Long.parseLong(idStr) : null;
    }

    /**
     * 获取当前用户类型
     * @param accessToken
     * @return
     */
    public String getUserType(String accessToken) {
        return getValue(parseToken(accessToken), USER_TYPE_KEY);
    }

    /**
     * 根据身份信息获取键值
     *
     * @param claims 身份信息
     * @param key 键
     * @return 值
     */
    public static String getValue(Claims claims, String key)
    {
        return Convert.toStr(claims.get(key), "");
    }
}
